package com.coderside.fragment.Reference;

import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.lang.StringUtils;

public class FNameUtil {

	//父字段
	private String parentField;

	//在集合中的下标
	private int index;

	//基本数据类型的field name
	private String baseTypefn;

	public FNameUtil(String pfield, int ind) {
		parentField = pfield;
		index = ind;
		baseTypefn = parentField + "[" + index + "]";
	}

	public FNameUtil(String docFieldName) {
		Set<String> indexSet = getBetweenSeparatorStr(docFieldName, '[', ']');
		if (indexSet.size() > 0 && indexSet.iterator().hasNext()) {
			String ind = indexSet.iterator().next();
			index = Integer.parseInt(ind);
		}
		String[] tempnames = docFieldName.split("[.]");
		parentField = tempnames[tempnames.length - 1];
		baseTypefn = parentField + "[" + index + "]";
	}

	public String getCollectionfn(String attri) {
		String fn = null;
		if (StringUtils.isEmpty(attri)) {
			fn = baseTypefn;
		} else {
			fn = baseTypefn + "." + attri;
		}
		return fn;
	}

	public String getMapfn(String mapkey, String attri) {
		String fn = null;
		if (StringUtils.isEmpty(attri)) {
			fn = baseTypefn + "." + mapkey;
		} else {
			fn = baseTypefn + "." + mapkey + "." + attri;
		}
		return fn;
	}

	public String getParentField() {
		return parentField;
	}

	public int getIndex() {
		return index;
	}
	/**
	 * <pre>
	 * 得到指定分隔符中间的字符串的集合,
	 *              说明: 1.分隔符为 ()，[]，{}，<> 中的一组
	 *                        2.得到的集合以 ASCII 的升序排列
	 *              如       String originStr="((([a]+[b])/[c])-24)+[d]";
	 *              则          getStrBetweenSeparator(originStr,"[","]"));
	 *                           返回结果集合有四个元素  [a, b, c, d],
	 *                          以 ASCII 的升序排列
	 * </pre>
	 *
	 * @param originStr 要提取的源字符串
	 * @param leftSeparator 左边的分隔符
	 * @param rightSeparator 右边的分隔符
	 * @return    		指定分隔符中间的字符串的集合
	 */
	public  Set<String> getBetweenSeparatorStr(final String originStr, final char leftSeparator, final char rightSeparator) {
		Set<String> variableSet = new TreeSet<String>();
		if (originStr == null) {
			return variableSet;
		}
		String sTempArray[] = originStr.split("(\\" + leftSeparator + ")");
		for (int i = 1; i < sTempArray.length; i++) {
			int endPosition = sTempArray[i].indexOf(rightSeparator);
			String sTempVariable = sTempArray[i].substring(0, endPosition);
			variableSet.add(sTempVariable);
		}
		return variableSet;
	}
}